package com.zhhq.utils;

import com.zhhq.model.Result;
import com.zhhq.model.VerificationCode;

import java.util.*;

/**
 * Created by HeChaobin on 2017-07-13.
 */
public class VerificationUtil {

    private static Map<String, VerificationCode> map = new HashMap<String, VerificationCode>();

    /**
     * 获取验证码
     * @param loginName 登录名
     * @return
     */
    public static Result getVerificationCode(String loginName) {
        // 清理过期的验证码
        removeOutDateCode();

        if (map.size() > 10000) {
            return ResultUtil.error(11, " 当前找回密码的人数过多，请稍后再试！");
        }

        VerificationCode code = map.get(loginName);
        if (code == null) {
            // 当前用户没有请求过验证，进行生成验证码
            Random random = new Random();
            int s = random.nextInt(8999) + 1000;
            VerificationCode newCode = new VerificationCode();
            newCode.setCode(s);
            map.put(loginName, newCode);
            return ResultUtil.success(s);
        } else {
            if (code.getRequestTimes() > 10) { // 5分钟内只能尝试找回密码10次
                return ResultUtil.error(11, " 5分钟内只能尝试找回密码10次,请稍后重试！");
            } else {
                // 用户重复点了找回密码连接，更新验证码
                Random random = new Random();
                int s = random.nextInt(8999) + 1000;
                code.setCode(s);
                code.setCreateTime(new Date());
                code.setRequestTimes(code.getRequestTimes() + 1);

                return ResultUtil.success(s);
            }
        }
    }

    /**
     * 验证验证码
     * @param loginName 用户名
     * @param code 验证码
     * @return
     */
    public static Result validateCode(String loginName, Integer code) {
        removeOutDateCode();

        VerificationCode verificationCode = map.get(loginName);
        if (verificationCode == null) {
            // 验证码过期
            return ResultUtil.error(11, " 验证码已过期！");
        }

        Integer realCode = verificationCode.getCode();
        if (realCode.equals(code)) {
            map.remove(loginName);
        } else {
            return ResultUtil.error(11, " 验证码不正确！");
        }

        return ResultUtil.success();
    }

    // 清理过期验证码
    public static void removeOutDateCode() {
        Date currentTime = new Date();
        Iterator<Map.Entry<String, VerificationCode>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, VerificationCode> entry = it.next();
            String key = entry.getKey();
            if (currentTime.getTime() - entry.getValue().getCreateTime().getTime() > 300000) { // 5分钟过期
                it.remove();
            }
        }
    }
}
